package com.pingan.stat.reposys.general.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.pingan.common.core.property.Properties;
import com.pingan.common.util.ShellExecutor;
import com.pingan.setting.general.entity.GeneralStatSettingBean;
import com.pingan.setting.general.service.GeneralStatSettingService;
import com.pingan.setting.money24url.entity.Money24UrlBean;
import com.pingan.stat.service.StatService;

@Component
public class GeneralIndexPageStatService implements StatService {

	@Properties(name = "reposys.general.output.path")
	private String outputPath;

	@Properties(name = "reposys.general.index.page")
	private String generalIndexPageStatShell;

	@Resource
	private GeneralStatSettingService generalStatSettingService;

	@Resource
	private ShellExecutor shellExecutor;

	private static final Log log = LogFactory.getLog("hive");

	public void dailyStat(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String yyyyMMdd = sdf.format(date);
		String output = outputPath + "/" + yyyyMMdd;

		log.info("----------------->>>>>>>>>>>>>>>>>> stat index page ");
		List<GeneralStatSettingBean> beans = generalStatSettingService
				.getGeneralStatSettingBeans();

		for (GeneralStatSettingBean bean : beans) {
			String[] params = new String[] { yyyyMMdd, output,
					bean.getSiteId(), bean.getDomain() };

			shellExecutor.excecute(generalIndexPageStatShell, params);
		}

	}

	public String getHQL(String yyyyMMdd, Money24UrlBean bean) {
		StringBuilder sb = new StringBuilder("select log_date, "
				+ Integer.valueOf(bean.getId()).toString()
				+ ",referurl, count(*) ");

		sb.append(" from " + bean.getSiteId() + ".pv where log_date='"
				+ yyyyMMdd + "' and ");

		if (bean.getMatchType() == 1) {
			sb.append(" url='" + bean.getUrl() + "' group by log_date,"
					+ Integer.valueOf(bean.getId()).toString() + ",referurl");
		} else {
			sb.append(" url like '" + bean.getUrl() + "%' group by log_date,"
					+ Integer.valueOf(bean.getId()).toString() + ",referurl");
		}

		return sb.toString();
	}
}
